
Imports System
Imports System.Collections
Imports System.Data.SqlClient
Imports System.Web.Mail
Imports System.Web.SessionState
Imports System.Web.UI.WebControls
Imports System.Web

Namespace _2bMatesSite.Common
	''' <summary>
	''' Common utilities.
	''' </summary>
	Public Class Utils
		Public Const SQL_ESCAPE_CHAR As String = "!"

		Public Shared Function GetTemplates() As ArrayList
			Dim result As New ArrayList()
			Dim tpl As BO.Template = Nothing
			Dim conn As SqlConnection = DBManager.GetUnmanagedConnection()

			Try
				Dim cmd As New SqlCommand("SELECT * FROM Templates")
				cmd.Connection = conn

				Dim dr As SqlDataReader = cmd.ExecuteReader()

				While dr.Read()
					tpl = New BO.Template(dr)
					result.Add(tpl)
				End While
				dr.Close()
			Finally
				conn.Close()
			End Try

			Return result
		End Function

		Public Shared Function GetTemplateByID(ByVal templateID As Integer) As BO.Template
			Dim tpl As BO.Template = Nothing
			Dim conn As SqlConnection = DBManager.GetUnmanagedConnection()

			Try
				Dim cmd As New SqlCommand("SELECT * FROM Templates WHERE ID=@ID")
				cmd.Connection = conn
				cmd.Parameters.Add("@ID", templateID)

				Dim dr As SqlDataReader = cmd.ExecuteReader()

				If dr.Read() Then
					tpl = New BO.Template(dr)
				End If
				dr.Close()
			Finally
				conn.Close()
			End Try

			Return tpl
		End Function

		Public Shared Sub SendMail(ByVal from As String, ByVal [to] As String, ByVal subject As String, ByVal body As String)
			Dim Message As New MailMessage()

			Message.From = from
			Message.[To] = [to]
			Message.Subject = subject
			Message.Body = body

			SmtpMail.SmtpServer = Constants.SMTP_SERVER
			SmtpMail.Send(Message)
		End Sub

		' SQL text search in the where clause
		Public Shared Function GetLikeSQL(ByVal text As String) As String
			Return "LIKE '%" + SQLEscapeLIKEText(text) + "%' ESCAPE '" + SQL_ESCAPE_CHAR + "'"
		End Function

		Public Shared Function SQLEscapeLIKEText(ByVal unescapedText As String) As String
			Dim escapedText As String = SQLEscapeText(unescapedText)

			escapedText = escapedText.Replace(SQL_ESCAPE_CHAR, SQL_ESCAPE_CHAR + SQL_ESCAPE_CHAR)
			escapedText = escapedText.Replace("%", SQL_ESCAPE_CHAR + "%")
			escapedText = escapedText.Replace("_", SQL_ESCAPE_CHAR + "_")
			escapedText = escapedText.Replace("[", SQL_ESCAPE_CHAR + "[")
			escapedText = escapedText.Replace("]", SQL_ESCAPE_CHAR + "]")
			escapedText = escapedText.Replace("^", SQL_ESCAPE_CHAR + "^")

			Return escapedText
		End Function

		' SQL text escaping for the LIKE statement
		Public Shared Function SQLEscapeText(ByVal unescapedText As String) As String
			Dim escapedText As String = unescapedText
			escapedText = escapedText.Replace("'", "''")
			Return escapedText
		End Function

		' Returns an array list of the ID's of the logged users
		' (without the currently logged one)
		Public Shared Function GetLoggedUsersIDs() As ArrayList
		'HttpSessionState curSession ) - not used any more.. must be removed kk
			Dim users As New ArrayList()

			Dim dtNow As DateTime = DateTime.Now

			For Each otherSession As HttpSessionState In Constants.SESSIONS.Values
				' Skip the current user
				'if ( (curSession != null && (curSession.SessionID == otherSession.SessionID) )
				'	continue;

				' Skip sessions with no logged in user
				Dim userIDObj As Object = otherSession(Constants.ssnUserID)
				If userIDObj = Nothing Then
					Continue For
				End If

				'skip session with no user activity for the last few minutes
				If DateTime.Compare(dtNow.AddMinutes(-Constants.ssnUserOnlineInterval), DirectCast(otherSession(Constants.ssnLastUserRequestTime), DateTime)) > 0 Then
					Continue For
				End If

				' Collect all others
				Dim userID As Integer = DirectCast(userIDObj, Integer)
				If Not users.Contains(userID) Then
					Dim loggedUser As BO.User = BO.Users.GetUserByID(DirectCast(userID, Integer))
					If loggedUser.ShowOnline Then
						users.Add(userID)
					End If
				End If
			Next

			Return users
		End Function

		' Retrieve the logged-in user, by it's ID, stored in the sesion object
		Public Shared Function GetLoggedUser(ByVal session As HttpSessionState) As BO.User
			Dim loggedUser As BO.User = Nothing

			Dim userID As Object = session(Constants.ssnUserID)
			If userID <> Nothing Then
				loggedUser = BO.Users.GetUserByID(DirectCast(userID, Integer))
			Else
				Dim userName As String = HttpContext.Current.User.Identity.Name
				If HttpContext.Current.User.Identity.IsAuthenticated Then
					Dim parts As String() = userName.Split(";"C)
					If parts.Length = 3 Then
						userID = Integer.Parse(parts(0))
						loggedUser = BO.Users.GetUserByID(DirectCast(userID, Integer))
					End If
				End If
			End If

			Return loggedUser
		End Function

		Public Shared Function CloneTableRow(ByVal srcRow As TableRow) As TableRow
			Dim row As New TableRow()
			row.CopyBaseAttributes(srcRow)

			Dim i As Integer = 0
			While i < srcRow.Cells.Count
				Dim cell As TableCell = CloneTableCell(srcRow.Cells(i))

				row.Cells.Add(cell)
				System.Math.Max(System.Threading.Interlocked.Increment(i),i - 1)
			End While

			row.BackColor = srcRow.BackColor
			row.BorderColor = srcRow.BorderColor
			row.BorderStyle = srcRow.BorderStyle
			row.BorderWidth = srcRow.BorderWidth
			row.CssClass = srcRow.CssClass
			row.ForeColor = srcRow.ForeColor
			row.Height = srcRow.Height
			row.HorizontalAlign = srcRow.HorizontalAlign
			row.VerticalAlign = srcRow.VerticalAlign
			row.Width = srcRow.Width

			Return row
		End Function

		Public Shared Function CloneTableCell(ByVal srcCell As TableCell) As TableCell
			Dim cell As New TableCell()

			cell.CopyBaseAttributes(srcCell)

			cell.BackColor = srcCell.BackColor
			cell.BorderColor = srcCell.BorderColor
			cell.BorderStyle = srcCell.BorderStyle
			cell.BorderWidth = srcCell.BorderWidth
			cell.ColumnSpan = srcCell.ColumnSpan
			cell.CssClass = srcCell.CssClass
			cell.ForeColor = srcCell.ForeColor
			cell.Height = srcCell.Height
			cell.HorizontalAlign = srcCell.HorizontalAlign
			cell.RowSpan = srcCell.RowSpan
			cell.VerticalAlign = srcCell.VerticalAlign
			cell.Width = srcCell.Width
			cell.Wrap = srcCell.Wrap

			' also copy the text
			cell.Text = srcCell.Text

			Return cell
		End Function

		Public Shared Function CloneTextBox(ByVal srcTextBox As TextBox) As TextBox
			Dim txt As New TextBox()

			txt.CopyBaseAttributes(srcTextBox)

			txt.BackColor = srcTextBox.BackColor
			txt.BorderColor = srcTextBox.BorderColor
			txt.BorderStyle = srcTextBox.BorderStyle
			txt.BorderWidth = srcTextBox.BorderWidth
			txt.CssClass = srcTextBox.CssClass
			txt.ForeColor = srcTextBox.ForeColor
			txt.Height = srcTextBox.Height
			txt.Width = srcTextBox.Width

			txt.AutoPostBack = srcTextBox.AutoPostBack
			txt.Columns = srcTextBox.Columns
			txt.MaxLength = srcTextBox.MaxLength
			txt.[ReadOnly] = srcTextBox.[ReadOnly]
			txt.Rows = srcTextBox.Rows
			txt.Text = srcTextBox.Text
			txt.TextMode = srcTextBox.TextMode
			txt.Wrap = srcTextBox.Wrap

			Return txt
		End Function

		Public Shared Function CloneRadioButton(ByVal srcRB As RadioButton) As RadioButton
			Dim rb As New RadioButton()

			rb.CopyBaseAttributes(srcRB)

			rb.GroupName = srcRB.GroupName

			rb.BackColor = srcRB.BackColor
			rb.BorderColor = srcRB.BorderColor
			rb.BorderStyle = srcRB.BorderStyle
			rb.BorderWidth = srcRB.BorderWidth
			rb.CssClass = srcRB.CssClass
			rb.ForeColor = srcRB.ForeColor
			rb.Height = srcRB.Height
			rb.Width = srcRB.Width

			Return rb
		End Function

		Public Shared Function CloneHyperLink(ByVal srcHL As HyperLink) As HyperLink
			Dim hl As New HyperLink()

			hl.CopyBaseAttributes(srcHL)

			hl.BackColor = srcHL.BackColor
			hl.BorderColor = srcHL.BorderColor
			hl.BorderStyle = srcHL.BorderStyle
			hl.BorderWidth = srcHL.BorderWidth
			hl.CssClass = srcHL.CssClass
			hl.ForeColor = srcHL.ForeColor
			hl.Height = srcHL.Height
			hl.Width = srcHL.Width

			hl.ImageUrl = srcHL.ImageUrl
			hl.NavigateUrl = srcHL.NavigateUrl
			hl.Target = srcHL.Target
			hl.Text = srcHL.Text

			Return hl
		End Function

		Public Shared Function CloneImage(ByVal srcImg As Image) As Image
			Dim img As New Image()

			img.CopyBaseAttributes(srcImg)

			img.BackColor = srcImg.BackColor
			img.BorderColor = srcImg.BorderColor
			img.BorderStyle = srcImg.BorderStyle
			img.BorderWidth = srcImg.BorderWidth
			img.CssClass = srcImg.CssClass
			img.ForeColor = srcImg.ForeColor
			img.Height = srcImg.Height
			img.Width = srcImg.Width

			img.AlternateText = srcImg.AlternateText
			img.ImageAlign = srcImg.ImageAlign
			img.ImageUrl = srcImg.ImageUrl

			Return img
		End Function

		Public Shared Sub RedirectToLoginPage(ByVal oPage As System.Web.UI.Page)
			Dim sPageASPName As String = oPage.Request.ServerVariables("SCRIPT_NAME").ToString()
			If sPageASPName.LastIndexOf("/") > -1 Then
				sPageASPName = sPageASPName.Substring(sPageASPName.LastIndexOf("/") + 1)
			End If

			oPage.Response.Redirect(Constants.LOGIN_PAGE + "?ref=" + sPageASPName + "&" + oPage.Request.QueryString.ToString())
		End Sub
	End Class
End Namespace






